<template>
    <el-dialog v-model="dialogFormVisible" :title='title' width="50%" align-center append-to-body
        :destroy-on-close='true'>
        <div class="dialog-content">
            <el-form :model="formData" label-width="120px" style="max-width: 600px;" :rules="rules"
                :label-position="labelPosition">
                <el-form-item label="主题" prop='message_title'>
                    <el-input v-model="formData.message_title" />
                </el-form-item>
                <el-form-item label="发布部门" prop='message_publish_department' v-if="title == '新增公告' || title == '编辑公告'">
                    <el-select v-model="formData.message_publish_department" placeholder="请选择发布部门">
                        <el-option v-for="item in options" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="发布人" prop='message_publish_name'>
                    <el-input v-model="formData.message_publish_name" />
                </el-form-item>
                <el-form-item label="接收部门" prop='message_receipt_object' v-if="title == '新增公告' || title == '编辑公告'">
                    <el-select v-model="formData.message_receipt_object" placeholder="请选择接收部门">
                        <!-- <el-option v-for="item in allOptions" :key="item.value" :label="item.value"
                       :value="item.value" /> -->
                         <el-option v-for="item in options" :key="item" :label="item" :value="item" />
                        <el-option key="全体成员" label="全体成员" value="全体成员" />
                    </el-select>
                </el-form-item>
                <el-form-item label="公告等级" prop='message_level' v-if="title == '新增公告' || title == '编辑公告'">
                    <el-select v-model="formData.message_level" placeholder="选择公告等级">
                        <el-option label="一般" value="一般" />
                        <el-option label="重要" value="重要" />
                        <el-option label="必要" value="必要" />
                    </el-select>
                </el-form-item>
                <el-form-item label="内容" prop='message_content'>
                    <div style="border: 1px solid #ccc">
                        <!-- wangEditor结构 -->
                        <Toolbar style="border-bottom: 1px solid #ccc;width: 600px;" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 300px; overflow-y: hidden;width: 600px;" v-model="valueHtml"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </el-form-item>

            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="yes">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, shallowRef } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getDepartment } from '@/api/setting/index'
import { publishMessage, editMessage } from '@/api/message/index'
import { ElMessage } from 'element-plus'
import { changeUserReadList } from '@/api/dep_msg/index'
import {useMsg} from '@/store/modules/message.ts'
const msgStore = useMsg()
const dialogFormVisible = ref<boolean>(false)
const title = ref('发布公告')
const labelPosition = ref('left')
const formData = reactive({
    message_title: '',
    message_publish_department: '',
    message_publish_name: '',
    message_receipt_object: '',
    message_level: '',
    message_content: '',
})
const rules = reactive({
    message_title: [
        { required: true, message: '请输入公告标题', trigger: 'blur' },
    ],
    message_publish_department: [
        { required: true, message: '请选择发布部门', trigger: 'blur' },
    ],
    message_publish_name: [
        { required: true, message: '请输入发布人', trigger: 'blur' },
    ],
    message_receipt_object: [
        { required: true, message: '请选择的接收对象', trigger: 'blur' },
    ],
    message_level: [
        { required: true, message: '请选择公告等级', trigger: 'blur' },
    ],
    message_content: [
        { required: true, message: '请输入公告内容', trigger: 'blur' },
    ],
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// mode
const mode = ref('default')
// 内容 HTML
const valueHtml = ref()
const toolbarConfig: any = {
    excludeKeys: []
}
const editorConfig = {
    placeholder: '',
    MENU_CONF: {
        // uploadImage: {
        // 	//上传图片配置
        // 	server: `${import.meta.env.VITE_API_BASEURL}/set/uploadCompanyPicture`, //上传接口地址
        // 	fieldName: 'file', //上传文件名
        // 	methods: 'post',
        // 	metaWithUrl: true, // 参数拼接到 url 上
        // 	// 单个文件上传成功之后
        // 	// onSuccess(file, res) {
        // 	// },
        // 	// 自定义插入图片
        // 	customInsert(res, insertFn) {
        // 		insertFn(res.url)
        // 	},
        // },
    }
}
// 上传图片，修改 uploadImage 菜单配置
// 需要注意的是，如何去修改参数？
toolbarConfig.excludeKeys = [
    'blockquote',
    'bgColor',
    'color',
    'group-more-style',
    'fontFamily',
    'bulletedList',
    'numberedList',
    'lineHeight',
    'todo',
    'emotion',
    'insertLink',
    'group-video',
    'insertTable',
    'codeBlock',
    'divider',
    'fullScreen',
    'group-image',

    // 排除菜单组，写菜单组 key 的值即可
]
const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
// 不包括全体成员
const options = ref([])
const returnDepartment = async () => {
    const res = await getDepartment()
    if (res.status == 0) {
        options.value = JSON.parse(res.data)
    }
}
returnDepartment()
//确定
const emit = defineEmits(['success'])
const yes = async () => {
    if (title.value == '新增公告' || title.value == '编辑公告') {
        let data: any = {
            ...formData,
            message_category: '公司公告',
            message_content: valueHtml.value
        }
        const res:any = title.value == '新增公告' ? await publishMessage(data) : await editMessage(data)
        if (res.status == 0) {
            ElMessage({
                message: title.value == '新增公告' ? '发布公告成功' : '编辑公告成功',
                type: 'success',
            })
           
            if(title.value == '新增公告'){
                let data:any = {
                    newId: res.id,
                    department:res.department
                }
                await changeUserReadList(data)
            }
            let id = localStorage.getItem('id')
            msgStore.returnReadList(id)
            emit('success') 
            dialogFormVisible.value = false
        } else {
            ElMessage({
                type: 'error',
                message: title.value == '新增公告' ? '发布公告失败' : '编辑公告失败'
            })
        }
    }else{
         let datas: any = {
            ...formData,
            message_category: '系统消息',
            message_content: valueHtml.value
        }
        const res = title.value == '新增系统消息' ? await publishMessage(datas) : await editMessage(datas)
        if (res.status == 0) {
            ElMessage({
                message: title.value == '新增系统消息' ? '新增系统消息成功' : '编辑系统消息失败',
                type: 'success',
            })
            let id = localStorage.getItem('id')
            msgStore.returnReadList(id)
            emit('success')
            dialogFormVisible.value = false
        } else {
            ElMessage({
                type: 'error',
                message: title.value == '新增系统消息' ? '新增系统消息失败' : '编辑系统消息失败'
            })
        }
    }
}

const ids = ref()
// 打开编辑管理员的弹窗
const open = (type: number, row: any) => {
    Object.assign(formData, {
        message_title: '',
        message_publish_department: '',
        message_publish_name: '',
        message_receipt_object: '',
        message_level: '',
        message_category: '',
        message_content: '',
    })
    valueHtml.value = ''
    if (type == 1) {
        if (row) {
            ids.value = row.id
            title.value = '编辑公告'
            valueHtml.value = row.message_content
            Object.assign(formData, { ...row })
        } else {
            title.value = '新增公告'
        }
    }else{
        if (row) {
            ids.value = row.id
            title.value = '编辑系统消息'
            valueHtml.value = row.message_content
            Object.assign(formData, { ...row })
        } else {
            title.value = '新增系统消息'
        }
    }

    dialogFormVisible.value = true
}

defineExpose({
    open
})
</script>

<style lang="scss" scoped>
.dialog-content {
    display: flex;
    padding: 20px 30px;
    flex: 1;
    max-height: 800px;
    overflow: auto;
}

.el-dialog__body {
    padding: 0;
}

.el-input {
    width: 240px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.el-form-item {
    margin: 16px;
}

:deep(.w-e-text-container p) {
    margin: 0;
}
</style>
